<template>
  <div class="video-player">
    <header class="player-header">
      <div class="header-content">
        <h1 class="video-title">{{ title || '视频播放器' }}</h1>
        <div class="player-controls">
          <button @click="toggleFullscreen" class="btn btn-secondary">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/>
            </svg>
            全屏
          </button>
          <button @click="closePlayer" class="btn btn-primary">关闭</button>
        </div>
      </div>
    </header>

    <main class="player-content">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载视频...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <h3>视频加载失败</h3>
        <p>{{ error }}</p>
        <button @click="retryLoad" class="btn btn-primary">重试</button>
      </div>

      <div v-else class="video-container" ref="videoContainer">
        <video 
          ref="videoElement"
          :src="videoUrl" 
          controls
          preload="metadata"
          class="video-element"
          @loadstart="onLoadStart"
          @loadeddata="onLoadedData"
          @error="onVideoError"
          @progress="onProgress"
          @timeupdate="onTimeUpdate"
          @ended="onVideoEnded"
        >
          <!-- 添加多种格式支持 -->
          <source :src="videoUrl" :type="videoMimeType">
          <p class="video-not-supported">
            您的浏览器不支持视频播放。
            <br>
            <a :href="videoUrl" download>点击下载视频</a>
          </p>
        </video>
        
        <!-- 视频信息显示 -->
        <div v-if="showVideoInfo" class="video-info">
          <div class="video-stats">
            <span class="video-duration">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
            <span class="video-format">{{ videoFormat }}</span>
            <span class="video-size">{{ fileSize }}</span>
          </div>
        </div>
        
        <!-- 不支持的视频格式提示 -->
        <div v-if="showUnsupportedWarning" class="unsupported-video">
          <div class="unsupported-icon">🎥</div>
          <h3>视频格式可能不兼容</h3>
          <p>当前浏览器可能不支持此视频格式，建议使用以下格式：</p>
          <ul class="supported-formats">
            <li>MP4 (H.264/AVC)</li>
            <li>WebM (VP8/VP9)</li>
            <li>OGG (Theora)</li>
          </ul>
          <div class="fallback-actions">
            <button @click="downloadVideo" class="btn btn-primary">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="7,10 12,15 17,10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
              下载视频
            </button>
            <button @click="openInNewTab" class="btn btn-secondary">
              在新窗口打开
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

// 状态管理
const loading = ref(true)
const error = ref<string | null>(null)
const videoElement = ref<HTMLVideoElement>()
const videoContainer = ref<HTMLDivElement>()
const showVideoInfo = ref(false)
const showUnsupportedWarning = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const fileSize = ref('')

// 从URL参数获取视频信息
const videoUrl = computed(() => {
  const url = route.query.url as string
  return url ? decodeURIComponent(url) : ''
})

const title = computed(() => {
  const titleParam = route.query.title as string
  return titleParam ? decodeURIComponent(titleParam) : '视频播放器'
})

// 视频格式检测
const videoFormat = computed(() => {
  const url = videoUrl.value.toLowerCase()
  if (url.includes('.mp4')) return 'MP4'
  if (url.includes('.webm')) return 'WebM'
  if (url.includes('.ogg') || url.includes('.ogv')) return 'OGG'
  if (url.includes('.avi')) return 'AVI'
  if (url.includes('.mov')) return 'MOV'
  if (url.includes('.wmv')) return 'WMV'
  if (url.includes('.flv')) return 'FLV'
  if (url.includes('.mkv')) return 'MKV'
  return '未知格式'
})

// MIME类型检测
const videoMimeType = computed(() => {
  const url = videoUrl.value.toLowerCase()
  if (url.includes('.mp4')) return 'video/mp4'
  if (url.includes('.webm')) return 'video/webm'
  if (url.includes('.ogg') || url.includes('.ogv')) return 'video/ogg'
  if (url.includes('.avi')) return 'video/x-msvideo'
  if (url.includes('.mov')) return 'video/quicktime'
  if (url.includes('.wmv')) return 'video/x-ms-wmv'
  if (url.includes('.flv')) return 'video/x-flv'
  if (url.includes('.mkv')) return 'video/x-matroska'
  return 'video/mp4' // 默认
})

// 判断是否为浏览器原生支持的格式
const isSupportedFormat = computed(() => {
  const url = videoUrl.value.toLowerCase()
  return url.includes('.mp4') || url.includes('.webm') || url.includes('.ogg')
})

// 加载视频
const loadVideo = async () => {
  loading.value = true
  error.value = null

  try {
    if (!videoUrl.value) {
      throw new Error('视频URL不能为空')
    }

    console.log('开始加载视频:', videoUrl.value)
    
    // 检查视频是否可访问
    const response = await fetch(videoUrl.value, { method: 'HEAD' })
    if (!response.ok) {
      throw new Error(`视频加载失败 (${response.status})`)
    }
    
    console.log('视频HEAD请求成功，准备加载视频元素')
    // HEAD请求成功，让视频元素开始加载
    loading.value = false

  } catch (err: any) {
    console.error('视频加载失败:', err)
    error.value = err.message || '视频加载失败'
    loading.value = false
  }
}

// 视频事件处理
const onLoadStart = () => {
  console.log('视频开始加载')
}

const onLoadedData = () => {
  console.log('视频数据加载完成')
  loading.value = false
  showVideoInfo.value = true
  
  // 获取视频时长
  if (videoElement.value) {
    duration.value = videoElement.value.duration || 0
  }
}

const onVideoError = (event: Event) => {
  console.error('视频播放错误:', event)
  const videoEl = event.target as HTMLVideoElement
  const videoError = videoEl.error
  
  loading.value = false
  
  let errorMessage = '视频播放失败'
  if (videoError) {
    switch (videoError.code) {
      case videoError.MEDIA_ERR_ABORTED:
        errorMessage = '视频加载被中止'
        break
      case videoError.MEDIA_ERR_NETWORK:
        errorMessage = '网络错误导致视频加载失败'
        break
      case videoError.MEDIA_ERR_DECODE:
        errorMessage = '视频解码失败'
        break
      case videoError.MEDIA_ERR_SRC_NOT_SUPPORTED:
        errorMessage = '不支持的视频格式或视频文件损坏'
        showUnsupportedWarning.value = true
        break
      default:
        errorMessage = '未知的视频播放错误'
    }
  }
  
  // 检查是否为不支持的格式
  if (!isSupportedFormat.value) {
    showUnsupportedWarning.value = true
    errorMessage = `不支持的视频格式 (${videoFormat.value})`
  }
  
  console.error('视频错误详情:', errorMessage, videoError)
  error.value = errorMessage
}

// 播放进度更新
const onProgress = () => {
  if (videoElement.value) {
    // 可以在这里处理缓冲进度
  }
}

// 时间更新
const onTimeUpdate = () => {
  if (videoElement.value) {
    currentTime.value = videoElement.value.currentTime || 0
  }
}

// 视频播放结束
const onVideoEnded = () => {
  console.log('视频播放完成')
  // 可以在这里添加播放完成的处理逻辑
}

// 重试加载
const retryLoad = () => {
  if (videoElement.value) {
    videoElement.value.load()
  }
  loadVideo()
}

// 全屏切换
const toggleFullscreen = () => {
  if (!videoContainer.value) return

  if (!document.fullscreenElement) {
    videoContainer.value.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

// 关闭播放器
const closePlayer = () => {
  window.close()
}

// 时间格式化
const formatTime = (time: number): string => {
  if (isNaN(time) || time <= 0) return '00:00'
  
  const hours = Math.floor(time / 3600)
  const minutes = Math.floor((time % 3600) / 60)
  const seconds = Math.floor(time % 60)
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  } else {
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }
}

// 下载视频
const downloadVideo = () => {
  if (videoUrl.value) {
    console.log('开始下载视频:', videoUrl.value)
    const link = document.createElement('a')
    link.href = videoUrl.value
    link.download = title.value || 'video'
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

// 在新窗口打开
const openInNewTab = () => {
  if (videoUrl.value) {
    window.open(videoUrl.value, '_blank')
  }
}

// 键盘快捷键
const handleKeyPress = (event: KeyboardEvent) => {
  if (!videoElement.value) return

  switch (event.code) {
    case 'Space':
      event.preventDefault()
      if (videoElement.value.paused) {
        videoElement.value.play()
      } else {
        videoElement.value.pause()
      }
      break
    case 'KeyF':
      event.preventDefault()
      toggleFullscreen()
      break
    case 'Escape':
      if (document.fullscreenElement) {
        document.exitFullscreen()
      }
      break
  }
}

// 页面加载时初始化
onMounted(() => {
  loadVideo()
  document.addEventListener('keydown', handleKeyPress)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyPress)
})
</script>

<style scoped>
.video-player {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;
}

.player-header {
  background: rgba(0, 0, 0, 0.8);
  border-bottom: 1px solid #333;
  padding: 1rem;
  position: relative;
  z-index: 10;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.video-title {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: white;
}

.player-controls {
  display: flex;
  gap: 0.5rem;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.player-content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
}

.loading-container, .error-container {
  text-align: center;
  padding: 2rem;
  color: white;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #333;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  color: #dc3545;
}

.error-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.video-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-element {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8px;
}

.video-not-supported {
  text-align: center;
  padding: 2rem;
  color: #fff;
  background: rgba(0, 0, 0, 0.8);
}

.video-not-supported a {
  color: #007bff;
  text-decoration: none;
}

.video-not-supported a:hover {
  text-decoration: underline;
}

.video-info {
  position: absolute;
  top: 1rem;
  right: 1rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.875rem;
  z-index: 10;
}

.video-stats {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.video-stats span {
  white-space: nowrap;
}

.unsupported-video {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 3rem;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  text-align: center;
  max-width: 500px;
  z-index: 10;
}

.unsupported-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.unsupported-video h3 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.5rem;
}

.unsupported-video p {
  color: #666;
  margin: 0 0 1.5rem 0;
  line-height: 1.5;
}

.supported-formats {
  text-align: left;
  margin: 1.5rem 0;
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.supported-formats li {
  color: #666;
  margin-bottom: 0.5rem;
  font-family: 'Courier New', monospace;
}

.fallback-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin-top: 2rem;
}

/* 全屏样式 */
.video-container:fullscreen {
  background: #000;
}

.video-container:fullscreen .video-element {
  width: 100%;
  height: 100%;
  border-radius: 0;
}
</style>




